package internal

import (
	"gitee.com/snxamdf/wui/wdb"
	"sync"
)

var _cache = map[string]string{}

func cacheDB() *wdb.DB {
	return wdb.GetDB("w_cache")
}

type Cache struct {
	lock sync.Mutex
}

func (m *Cache) Put(key string, value string) {
	m.lock.Lock()
	defer m.lock.Unlock()
	if err := cacheDB().Put(key, value); err == nil {
		_cache[key] = value
	}
}

func (m *Cache) Get(key string) string {
	m.lock.Lock()
	defer m.lock.Unlock()
	if data, ok := _cache[key]; ok {
		return data
	} else {
		if byt := cacheDB().Get(key); byt == nil {
			return ""
		} else {
			var v = string(byt)
			_cache[key] = v
			return v
		}
	}
}

func (m *Cache) Del(key string) {
	cacheDB().Delete(key)
	delete(_cache, key)
}
